package com.btb.adapter.schedule;

import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.btb.adapter.constant.Constants;
import com.btb.adapter.model.TaskConfig;
import com.btb.adapter.service.TaskConfigService;
import com.btb.adapter.service.WatchTransferService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
//@Component
@EnableScheduling
public class BuySuccessSchedule {

	@Autowired
	private TaskConfigService taskConfigService;
	@Autowired
	private WatchTransferService watchTransferService;

	@Scheduled(initialDelay = 100, fixedDelay = 1000 * 1)
	public void buySuccessSchedule() {
		log.error("BuySuccessSchedule is start");
		try {
			final TaskConfig taskConfig= taskConfigService.findConfigByTaskNameCache(Constants.BUY_SUCCESS);
			if(Objects.isNull(taskConfig)) {
				log.error("BuySuccessSchedule taskConfig is null");
				return;
			}
			Long status = Optional.ofNullable(taskConfig.getStatus()).orElse(1L);
			if(Objects.equals(1L, status)) {
				log.error("BuySuccessSchedule taskConfig status is 1 stop");
				return;
			}
			BigInteger maxBlockNumber = watchTransferService.getBlockNumber();
			Long startBlockNumber = taskConfig.getStartBlockNumber();
			if(startBlockNumber.longValue() >= maxBlockNumber.longValue()) {
				log.error("WatchTransferJob id:{} startBlockNumber > blockNumber is stop startBlockNumber:{},blockNumber:{}", taskConfig.getId(),startBlockNumber,maxBlockNumber);
				return;
			}
			Long stepNum = taskConfig.getStepNum();
			int end = startBlockNumber.intValue() + stepNum.intValue();
			int newEnd = Math.min(end, maxBlockNumber.intValue());
			boolean event = watchTransferService.event(String.valueOf(startBlockNumber), String.valueOf(newEnd));
			log.error(
					"WatchTransferJob id:{},initBlockNumber:{},maxBlockNumber:{},startBlockNumber:{},endBlockNumber:{} = > "
							+ " runing result:{}",
					taskConfig.getId(), taskConfig.getInitBlockNumber(),maxBlockNumber,startBlockNumber, newEnd, event);
			if (Objects.equals(event, true)) {
				taskConfigService.updateStartBlockNumber(taskConfig.getId(), new Long(newEnd));
			} else {
				// 把起始区块,往后更新一个, 以此保证任务可以继续
				taskConfigService.updateStartBlockNumber(taskConfig.getId(), startBlockNumber - 1);
			}
		} catch (Exception e) {
			log.error("BuySuccessSchedule err:{}", e.getMessage(), e);
		}
		log.error("BuySuccessSchedule is end");
	}
}
